
const path = '';
const request = axios.create({baseURL: path + '/api', timeout: 60000})
request.interceptors.response.use(res => {
    if (res && res.data.code === 502) {
        // 跳转到登录页
        window.location.reload()
    }
    return res;
}, error => {
    return Promise.reject(error);
});

/**
 * 异步加载组件
 * @param tplPath 组件路径
 * @returns {(function(*, *): void)|*}
 */
function isExternal(path) {
    return /^(https?:|mailto:|tel:)/.test(path)
}

const JS_MAP = {
    'vue-router': '/assets/js/vue-router.global.js',
    'lodash-es': '/assets/js/lodash.min.js',
    'nprogress': '/assets/nprogress/nprogress.js',
    'screenfull': '/assets/js/screenfull.js',
}
const CSS_MAP = {
    'nprogress/nprogress.css': '/assets/nprogress/nprogress.css',
}

function lazyImport(tplPath) {
    if (!tplPath.startsWith("/")) {
        tplPath = "/" + tplPath
    }
    const {loadModule} = window['vue3-sfc-loader'];
    const options = {
        moduleCache: {
            vue: Vue,
            'vue-router': VueRouter,
            'vueuse/core': VueUse,
            'pinia': Pinia,
            'element-plus': ElementPlus,
            '@element-plus/icons-vue': ElementPlusIconsVue,
            sass: {},
            scss: {}
        },
        async getFile(url) {
            if (JS_MAP[url]) {
                url = JS_MAP[url]
            }
            if (CSS_MAP[url]) {
                url = CSS_MAP[url]
            }
            if (url.startsWith("@")) {
                url = '/assets' + url.substring(1, url.length)
                if (url.endsWith('.png')) {
                    return {type: ".png"}
                }
                if (url.endsWith('.jpg')) {
                    return {type: ".jpg"}
                }
                if (url.endsWith('.svg')) {
                    return {type: ".svg"}
                }
                if (!url.endsWith(".js")) {
                    url = url + '.js'
                }
            }
            let type = ''
            if (/.*?\.js|.mjs$/.test(url)) {
                type = ".mjs"
            } else if (/.*?\.css$/.test(url)) {
                type = ".css"
            } else {
                type = ".vue"
            }
            if (type === '.vue') {
                url = '/tpl' + url
            }
            const res = await fetch(url);
            if (!res.ok) {
                throw Object.assign(new Error(res.statusText + ' ' + url), {res});
            }
            return {
                getContentData: asBinary => asBinary ? res.arrayBuffer() : res.text(),
                type: type
            }
        },
        addStyle(textContent, scopeId) {
            if (scopeId && scopeId.endsWith("css")) {
                let linkElement = document.createElement('link');
                linkElement.setAttribute('rel', 'stylesheet')
                linkElement.setAttribute('type', 'text/css')
                linkElement.setAttribute('href', CSS_MAP[scopeId] ? CSS_MAP[scopeId] : scopeId)
                document.head.insertBefore(linkElement,
                    document.head.getElementsByTagName('style')[0] || null)
            } else {
                if (textContent && textContent.trim() && scopeId) {
                    textContent = textContent.trim()
                    const style = Object.assign(document.createElement('style'), {textContent});
                    const ref = document.head.getElementsByTagName('style')[0] || null;
                    style.id = scopeId.replace('data-v-', '')
                    document.head.insertBefore(style, ref);
                }
            }
        },
        async handleModule(type, getContentData, path, options) {
            switch (type) {
                case '.css':
                    options.addStyle(await getContentData(false), path);
                    return null
                case '.jpg':
                case '.svg':
                case '.png':
                    return '/assets' + path.replace("@", "")
                // console.log(type, getContentData, path, options)
                // return await getContentData()
            }
        },
        log(type, ...data) {
            if (type === 'error') {
                console.error(data[0], data[1])
            }
        }

    }
    if (tplPath.endsWith(".js")) {
        return loadModule(tplPath, options);
    } else {
        return Vue.defineAsyncComponent(() => loadModule(tplPath + '.vue', options));
    }
}

function registerIcons(app) {
    /*
     * 全局注册 Icon
     * 使用方式: <Icon name="name" size="size" color="color" />
     * 详见<待完善>
     */
    app.component('Icon', Icon)

    /*
     * 全局注册element Plus的icon
     */
    const icons = ElementPlusIconsVue
    for (const i in icons) {
        app.component(icons[i].name, icons[i])
        app.component(`el-icon-${icons[i].name}`.toLowerCase(), icons[i])
        app.component(`el-icon-${icons[i].name}`, icons[i])
    }
}

// Vue.use(Vuex)
// var store = new Vuex.Store({
//     modules: {
//         app: storeApp(), settings: storeSettings(), // user
//     }, getters: {
//         sidebar: state => state.app.sidebar,
//         device: state => state.app.device,
//         token: state => '',
//         avatar: state => '',
//         name: state => 'state.user.name'
//         // token: state => state.user.token,
//         // avatar: state => state.user.avatar,
//         // name: state => state.user.name
//     }
// })